package com.flyme.module.base.provider.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyme.common.core.aliyun.sms.AliSmsUtil;
import com.flyme.common.core.aliyun.sms.SmsTempEnum;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.utils.DateUtils;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
import com.flyme.module.base.client.entity.*;
import com.flyme.module.base.provider.mapper.SysUserexaminationMapper;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.order.client.entity.Order;
import com.flyme.module.order.client.enums.OrderStatusEnum;
import com.flyme.module.order.client.enums.OrderTypeEnum;
import com.flyme.module.order.provider.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysUserexaminationServiceImpl extends BaseServiceImpl<SysUserexaminationMapper, SysUserexamination> implements SysUserexaminationService {
    @Autowired
    private SysExatimeService sysExatimeService;
    @Autowired
    private SysExamseasonService sysExamseasonService;
    @Autowired
    private SysExaminationService sysExaminationService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SysUserService userService;

    @Override
    public List<EntityMap> getexamUserdetail(Long userId, Long userExamId) {
        CriteriaQuery<EntityMap> userexaminationCriteriaQuery=new CriteriaQuery();
        userexaminationCriteriaQuery.eq("userId",userId);
        userexaminationCriteriaQuery.eq("id",userExamId);
        return listEntityMaps(userexaminationCriteriaQuery);
    }

    @Override
    public Boolean updateSysuserexam(Long id) {
        SysUserexamination userexamination=getById(id);
        SysUser user = userService.getById(userexamination.getUserId());
        String examTimeId=userexamination.getExatimeId();
        Map<String, String> params = new HashMap<>();
        if(examTimeId.contains(",")) {
            String[] examStr = examTimeId.split(",");
            for (String s : examStr) {
                SysExatime sysExatime = sysExatimeService.getById(Long.parseLong(s));
                SysExamseason sysExamseason=sysExamseasonService.getById(sysExatime.getExamseasonId());
                SysExamination examination=sysExaminationService.getById(sysExamseason.getExaminationId());
//                sysExatime.setSignlastCount(sysExatime.getSignlastCount() + 1);
//                sysExatimeService.saveOrUpdate(sysExatime);
                String html=examination.getExaminationHtml().replaceAll("kaoshi.cbstudy.com/","");
                String examDate=sysExatime.getExamTime()+" "+sysExatime.getExamStartTime()+"-"+sysExatime.getExamendTime();
                String json="{\"mtname\":"+sysExamseason.getChildexamName()+",mttime\":"+examDate+",submittime\":"+html+"}";
                params.put("mtname", examination.getExamName());
                params.put("mttime", examDate);
                params.put("submittime", examination.getExaminationHtml());
                //发送考试通知
                AliSmsUtil.sendSmsCode(SmsTempEnum.EXAM,user.getMobile(), params);
            }
        }else{
            SysExatime sysExatime = sysExatimeService.getById(Long.parseLong(examTimeId));
            SysExamseason sysExamseason=sysExamseasonService.getById(sysExatime.getExamseasonId());
            SysExamination examination=sysExaminationService.getById(sysExamseason.getExaminationId());
//            sysExatime.setSignlastCount(sysExatime.getSignlastCount() + 1);
//            sysExatimeService.saveOrUpdate(sysExatime);
            String json="{\"mtname\":"+sysExamseason.getChildexamName()+",mttime\":"+sysExatime.getExamTime()+",submittime\":"+sysExatime.getExamStartTime()+"-"+sysExatime.getExamendTime()+"}";
            String examDate = sysExatime.getExamTime()+" "+sysExatime.getExamStartTime()+"-"+sysExatime.getExamendTime();
            params.put("mtname", examination.getExamName());
            params.put("mttime", examDate);
            params.put("submittime", examination.getExaminationHtml());
            //发送考试通知
            AliSmsUtil.sendSmsCode(SmsTempEnum.EXAM,user.getMobile(), params);
        }
        UpdateWrapper u = new UpdateWrapper();
        return update(u.set(true, "examStatus", 1).set(true,"payTime", DateUtils.getDateTime()).eq(true, "id", id));

    }

    @Override
    public List<EntityMap> getuserExamination(Long userId,Long examinationId ,String exatimeId) {
        CriteriaQuery<EntityMap> userexaminationCriteriaQuery=new CriteriaQuery();
        userexaminationCriteriaQuery.select("*");
        userexaminationCriteriaQuery.eq("userId",userId);
        userexaminationCriteriaQuery.eq("exatimeId",exatimeId);
        userexaminationCriteriaQuery.eq("examinationId",examinationId);
        return listEntityMaps(userexaminationCriteriaQuery);
    }

    @Override
    public EntityMap checkByUser(Long userId, Long examinationId){
        EntityMap map = new EntityMap();
        map.put("isApply", "0");
        map.put("addExa", "0");
        QueryWrapper<SysUserexamination> ux = new QueryWrapper();
        List<SysUserexamination> list = list(ux.eq("userId",userId).eq("examinationId",examinationId).ne("examStatus",3));
        if(list.size() > 0){
            map.put("isApply", "1");
            for(SysUserexamination sue : list){
                if(sue.getExamStatus().equals(0)){
                    Order order = orderService.checkUserOrder(sue.getId(), userId);
                    map.put("orderId", order.getId());
                }
                if(sue.getExamStatus().equals(1) || sue.getExamStatus().equals(2)){
                    map.put("addExa", "1");
                }
            }
        }
        return map;
    }

    @Override
    public EntityMap checkByUsercert(Long userId, Long examinationId,Long usercertificateId){
        EntityMap map = new EntityMap();
        map.put("isApply", "0");
        map.put("addExa", "0");
        QueryWrapper<SysUserexamination> ux = new QueryWrapper();
        List<SysUserexamination> list = list(ux.eq("userId",userId).eq("examinationId",examinationId).eq("usercertificateId",usercertificateId).ne("examStatus",3));
        if(list.size() > 0){
            map.put("isApply", "1");
            for(SysUserexamination sue : list){
                if(sue.getExamStatus().equals(0)){
                    Order order = orderService.checkUserOrder(sue.getId(), userId);
                    map.put("orderId", order.getId());
                }
                if(sue.getExamStatus().equals(1) || sue.getExamStatus().equals(2)){
                    map.put("addExa", "1");
                }
            }
        }
        return map;
    }

    /**
     * 订单定时器
     */
    @Override
    public void orderJobCheck() {
        DateTime dateTime = DateUtil.offsetHour(DateUtil.date(), -12);
        QueryWrapper<Order> qw = new QueryWrapper();
        List<Order> orders = orderService.list(qw.ne("orderEntity", OrderTypeEnum.examnation.code).eq("orderStatus", OrderStatusEnum.unpaid.code).lt("createTime", dateTime.toString()));
        if (orders.size() > 0) {
            for (Order order : orders) {
                order.setOrderStatus(OrderStatusEnum.close);
                order.setCloseDate(DateTime.now().toDateStr());
            }
            orderService.updateBatchById(orders);
        }
        DateTime dateTime2 = DateUtil.offsetMinute(DateUtil.date(), -5);
        QueryWrapper<Order> qw2 = new QueryWrapper();
        List<Order> signUpOrder = orderService.list(qw2.eq("orderEntity", OrderTypeEnum.examnation.code).eq("orderStatus", OrderStatusEnum.unpaid.code).lt("createTime", dateTime2.toString()));
        if (signUpOrder.size() > 0) {
            List<String> list = new ArrayList<>();
            for (Order order : signUpOrder) {
                order.setOrderStatus(OrderStatusEnum.close);
                order.setCloseDate(DateTime.now().toDateStr());
                list.add(String.valueOf(order.getTargetId()));
            }
            orderService.updateBatchById(signUpOrder);
            List<SysUserexamination> ueList = list(q().in("id", list));
            List<String> eIds = new ArrayList<>();
            for(SysUserexamination sue : ueList){
                sue.setExamStatus(3);
                String exatimeIds = sue.getExatimeId();
                String[] ids = exatimeIds.split(",");
                for(String exId : ids){
                    eIds.add(exId);
                }
            }
            updateBatchById(ueList);
            QueryWrapper<SysExatime> qw3 = new QueryWrapper();
            List<SysExatime> extimeList = sysExatimeService.list(qw3.in("id", eIds));
            for(SysExatime exatime : extimeList){
                if(exatime.getSignlastCount() < 1){
                    continue;
                }
                exatime.setSignlastCount(exatime.getSignlastCount() - 1);
            }
            if(extimeList.size() > 0){
                sysExatimeService.updateBatchById(extimeList);
            }
        }
    }

    @Override
    public List<EntityMap> getlastExamination(Long userId, Long certificateId) {
        CriteriaQuery<EntityMap> userexaminationCriteriaQuery=new CriteriaQuery();
        userexaminationCriteriaQuery.select("*");
        userexaminationCriteriaQuery.eq("userId",userId);
        userexaminationCriteriaQuery.eq("usercertificateId",certificateId);
        userexaminationCriteriaQuery.orderByDesc("createTime");
        return listEntityMaps(userexaminationCriteriaQuery);
    }

    @Override
    public SysUserexamination findByCode(Long userId, Long examinationId){
        return getOne(q().eq("userId", userId).eq("examinationId", examinationId).ne("examStatus", 0).ne("examStatus", 3), false);
    }
}
